#include "Panel.hpp"

Panel::Panel(int x, int y, int width, int height, int format):InterfaceElement(x, y, width, height){
    formatType = format;
}

Panel::Panel(){
    formatType = Panel::Static;
	setPosition(0, 0);
	setSize(100, 100);
}
    
void Panel::add(sf::Drawable* element){
    elements.push_back(element);
}

/** 
* Add an interface element to the panel.
*/
void Panel::add(InterfaceElement* element){
    interfaceElements.push_back(element);
    elements.push_back(element);
    element->parent = this;
}

/** 
* Remove an interface element from the panel.
*/
void Panel::remove(InterfaceElement* element){
    for (unsigned int i = 0; i < elements.size(); i++) {
        if (elements.at(i) == element) {
            elements.erase(elements.begin() + i);
            break;
        }
    }
    for (unsigned int i = 0; i < interfaceElements.size(); i++) {
        if (interfaceElements.at(i) == element) {
            interfaceElements.erase(interfaceElements.begin() + i);
            break;
        }
    }
}

void Panel::clear(){
    elements.clear();
    interfaceElements.clear();
}

InterfaceElement* Panel::collisionCheck(int x, int y){
    if(!InterfaceElement::collisionCheck(x, y))
        return 0;
    
    //Check for collision on any element in panel.
    for(unsigned int i = 0; i < interfaceElements.size(); i++){
        if(interfaceElements.at(i)->visible){
            InterfaceElement* collisionElement;
            collisionElement = interfaceElements.at(i)->collisionCheck(x - rect.left, y - rect.top);
            if(collisionElement != 0)
                return collisionElement;
        }
    }
    
    return this;
}

void Panel::draw(sf::RenderTarget& target, sf::RenderStates states) const {
    states.transform *= sf::Transform().translate((float)rect.left, (float)rect.top);
    for(unsigned int i = 0; i < elements.size(); i++){
        target.draw(*elements.at(i), states);    
    }
}

void Panel::update(unsigned int time){
    for(unsigned int i = 0; i < interfaceElements.size(); i++){
        interfaceElements.at(i)->update(time);
    }
}

void Panel::onResize(int width, int height){
    //Check if panel needs to resize.
    if(formatType & Panel::VerticalStretch)
        rect.height = height;
    if(formatType & Panel::HorizontalStretch)
        rect.width = width;
    if(formatType & Panel::BindBottom)
        rect.top = height - rect.height;
    if(formatType & Panel::BindRight)
        rect.left = width - rect.width;
    
    //Update panel contents incase size changed.
    for(unsigned int i = 0; i < interfaceElements.size(); i++){
        interfaceElements.at(i)->onResize(rect.width, rect.height);
    }
}

Panel::~Panel(){
    interfaceElements.clear();
    elements.clear();
}